<template>
  <el-dialog title="数据填报" :visible="visible" append-to-body :close-on-click-modal="false" width="1200px"
             :before-close="onClose" @open="onOpen">
    <el-form ref="form" :model="submitForm" :rules="submitFormRules" label-width="100px" label-suffix="："
             label-position="right">
      <el-form-item label="填报日期" prop="time">
        <el-date-picker v-model="submitForm.time" value-format="yyyyMMdd"/>
      </el-form-item>
      <el-form-item label="填报数据" prop="rows">
        <el-button type="warning" icon="el-icon-plus" size="small" round @click="onAddRow">添加数据行</el-button>
        <div class="rows">
          <el-input placeholder="区域数据" class="input" v-for="(item,index) in submitForm.rows" :key="index"
                    v-model="item.value">
            <el-select slot="prepend" v-model="item.name" placeholder="选择区域" filterable allow-create class="select">
              <el-option v-for="item in cities" :label="item" :value="item"/>
            </el-select>
            <el-button slot="append" icon="el-icon-delete-solid" @click="onRemoveRow(index)"></el-button>
          </el-input>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="onSubmit">保存并生成图表</el-button>
      <el-button @click="onClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {Message} from "element-ui";
  import {CACHE_KEYS} from "@/utils/cache";
  import {add, divide} from "lodash-es";

  export default {
    name: "SubmitData",
    props: {
      visible: {type: Boolean, default: false}
    },
    data() {
      return {
        cities: [],
        submitForm: {
          time: '',
          rows: []
        },
        submitFormRules: {
          time: [{required: true, message: '请选择填报日期', trigger: 'change'}],
          rows: [{
            required: true, message: '请添加区域数据', trigger: 'change',
            validator: (rule, value, callback) => {
              if (!value.length) callback(new Error('请添加区域数据'))
              else if (value.some(item => !item.name || !item.value)) callback(new Error('区域数据不能空'))
              else callback()
            }
          }]
        }
      }
    },
    methods: {
      onClose() {
        this.$emit('update:visible', false)
      },
      async onOpen() {
        if (!this.submitForm.rows.length) {
          const cities = await this.cache.get(CACHE_KEYS.CITIES)
          this.cities = cities || []
          if (this.cities.length) {
            this.cities.forEach(name => {
              this.submitForm.rows.push({name, value: '', percent: 1})
            })
          }
        }
      },
      onAddRow() {
        this.submitForm.rows.push({name: '', value: '', percent: 1})
      },
      onRemoveRow(index) {
        this.submitForm.rows.splice(index, 1)
      },
      onSubmit() {
        this.$refs.form.validate(async v => {
          if (v) {
            const {time, rows} = this.submitForm
            let data = await this.cache.get(time)
            if (data) {
              Message.error(`已存在${time}的数据，请确认`)
            } else {
              rows.forEach(row => {
                row.value *= 1
              })
              const totalArr = await this.cache.get(CACHE_KEYS.TOTAL)
              if (totalArr) {
                rows.forEach(row => {
                  const t = totalArr.find(x => x.name === row.name)
                  row.percent = t ? divide(row.value, add(row.value, t.value)) : 1
                })
              }
              await this.onSuccess(time, rows)
            }
          }
        })
      },
      async onSuccess(time, rows) {
        Message.success('保存成功')
        await this.cache.set(time, rows)
        await this.cache.setTotal(rows)
        this.$emit('success', {time, rows})
        this.cities.splice(0)
        this.$refs.form.resetFields()
        this.onClose()
      }
    },
  }
</script>

<style scoped lang="less">
  :deep(.el-dialog__body) {
    max-height: 500px;
    overflow-y: scroll;
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .rows {
    margin-top: 10px;

    display: flex;
    flex-direction: row;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;

    .input {
      width: 320px;

      :deep(.el-input__inner) {
        text-align: center;
      }
    }

    .select {
      width: 120px;
    }
  }

</style>